package one2Ten;

import java.util.Date;

/**
 * 输入一个整数，输出该数二进制表示中1的个数，其中负数用补码表示
 * 两种思路
 * 1、用1去位与操作，每步左移一位，低位到高位逐个判断
 * 2、每次将最后一个1变为0
 * Created by Wongy on 2018/3/13.
 */
public class Ten10 {
    private static int solution1(int n) {
        int count = 0;
        int flag = 1;
        while (flag != 0) {
            if ((n & flag) != 0) {
                count++;
            }
            flag = flag << 1;
        }
        return count;
    }

    private static int solution2(int n) {
        int count = 0;
        while (n != 0) {
            n = n & (n - 1);
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
        Date date1 = new Date();
        int result1 = solution1(0x7fffffff);
        Date date2 = new Date();
        int result2 = solution2(0x7fffffff);
        Date date3 = new Date();
        System.out.println("Ten10.main , 35 : " + result1 + " , time : " + (date2.getTime() - date1.getTime()));
        System.out.println("Ten10.main , 36 : " + result2 + " , time : " + (date3.getTime() - date2.getTime()));
    }
}
